#include "texture_quad.h"
#include "direct3d9.h"

TextureQuad::TextureQuad() {
	x = kx = y = ky = width = height = texture_width = texture_height = 0;
	this->v[0].z =
		this->v[1].z =
		this->v[2].z =
		this->v[3].z = 0.5f;

	this->v[0].col =
		this->v[1].col =
		this->v[2].col =
		this->v[3].col = 0xFFFFFFFF;

	v[0].tx = v[0].ty = v[1].ty = v[3].tx = 0.0f;
	v[1].tx = v[2].tx = v[2].ty = v[3].ty = 1.0f;

	// this->blend = D3D9App::BLEND_DEFAULT;
	tex = nullptr;
}

void TextureQuad::load(IDirect3DTexture9* texture) {
	width = g_pD3D9App->Texture_GetWidth(texture, false);
	height = g_pD3D9App->Texture_GetHeight(texture, false);
	texture_width = g_pD3D9App->Texture_GetWidth(texture, false);
	texture_height = g_pD3D9App->Texture_GetHeight(texture, false);
	tex = texture;
	update();
}


void TextureQuad::setXY(int x, int y) {
	this->x = x;
	this->y = y;
	update();
}

void TextureQuad::setRect(int kx, int ky, int width, int height) {
	this->kx = kx;
	this->ky = ky;
	this->width = width;
	this->height = height;
	update();
}

void TextureQuad::update() {
	auto& vertexs = this->v;
	vertexs[0].tx = vertexs[3].tx = kx * 1.0f / texture_width;
	vertexs[0].ty = vertexs[1].ty = ky * 1.0f / texture_height;
	vertexs[1].tx = vertexs[2].tx = (kx + width) * 1.0f / texture_width;
	vertexs[2].ty = vertexs[3].ty = (ky + height) * 1.0f / texture_height;

	float x1, y1, x2, y2;
	x1 = 0.0f; // -_anX * _w * _scaleX;
	y1 = 0.0f; // -_anY * _h * _scaleY;
	x2 = width; // (_w - _anX * _w)* _scaleX;
	y2 = height; // (_h - _anY * _h)* _scaleY;

	vertexs[0].x = x1 + x; vertexs[0].y = y1 + y;
	vertexs[1].x = x2 + x; vertexs[1].y = y1 + y;
	vertexs[2].x = x2 + x; vertexs[2].y = y2 + y;
	vertexs[3].x = x1 + x; vertexs[3].y = y2 + y;
}

void TextureQuad::setAlpha(unsigned char alpha) {
	v[0].col = v[1].col = v[2].col = v[3].col = 0x00FFFFFF | (alpha << 24);
}


void TextureQuad::render() {
	g_pD3D9App->Gfx_RenderQuad(v, tex, D3D9App::BLEND_DEFAULT);
}
